﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AgileSaude.Business;
using Uol.PagSeguro.Domain;
using AgileSaude.Entities;
using System.Reflection;
using System.Drawing;
using System.IO;

namespace AgileSaude.Web.Admin
{
    public partial class ConsultarCompras : System.Web.UI.Page
    {
        private string sortExpression
        {
            get { return ViewState["sortExpression"].ToString(); }
            set { ViewState["sortExpression"] = value; }
        }
        private int sortDirection
        {
            get { return Convert.ToInt32(ViewState["sortDirection"]); }
            set { ViewState["sortDirection"] = value; }
        }
        private int totalPages
        {
            get { return Convert.ToInt32(ViewState["totalPages"]); }
            set { ViewState["totalPages"] = value; }
        }
        private int pageNumber
        {
            get { return Convert.ToInt32(ViewState["pageNumber"]); }
            set { ViewState["pageNumber"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                sortExpression = "Data";
                sortDirection = 1;

                ddlMedico.DataTextField = "Nome";
                ddlMedico.DataValueField = "IdMedico";

                MedicoEntities medico = new MedicoEntities();
                Resultado resultado = new Resultado();

                ddlMedico.DataSource = new MedicoFacade().Listar(medico, ref resultado).OrderBy(x => x.Nome);
                ddlMedico.DataBind();

                ddlMedico.Items.Insert(0, "");

            }
        }

        protected void btnConsultar_Click(object sender, EventArgs e)
        {
            pageNumber = 1;
            PreencheGrid();
        }

        private void PreencheGrid()
        {
            try
            {

                //PagSeguroFacade pagseguroFacade = new PagSeguroFacade(Server.MapPath("~/Configuration/PagSeguroConfig.xml"));

                DateTime dtIni = DateTime.Parse("01/" + txtDataIni.Text);
                DateTime dtFim = DateTime.Parse(DateTime.DaysInMonth(dtIni.Year, dtIni.Month) + "/" + txtDataIni.Text);

                //TransactionSearchResult result = pagseguroFacade.ConsultaPorData(dtIni, dtFim, pageNumber);
                //totalPages = result.TotalPages;

                //List<PedidoEntities> Pedidos = new PedidoFacade().CopyFromPagSeguro(result);

                int medico;
                if (!int.TryParse(ddlMedico.SelectedValue, out medico))
                    medico = 0;

                List<PedidoEntities> Pedidos = new PedidoFacade().ListarPorData(dtIni, dtFim, medico);

                if (Pedidos.Count() > 0)
                {
                    btnAtualizarStatus.Visible = true;
                    btnExport.Visible = true;
                }
                ((Label)Master.FindControl("lblMensagem")).Visible = false;
                OrdenarLista(ref Pedidos);
                gvConsulta.DataSource = Pedidos;
                gvConsulta.DataBind();
                gvConsulta.Visible = true;
            }
            catch (Exception ex)
            {
                gvConsulta.Visible = false;
                ((Label)Master.FindControl("lblMensagem")).Text = ex.Message;
                ((Label)Master.FindControl("lblMensagem")).CssClass = "failureNotification";
                ((Label)Master.FindControl("lblMensagem")).Visible = true;
            }
        }

        private void OrdenarLista(ref List<PedidoEntities> listaCidade)
        {
            listaCidade.Sort(delegate(PedidoEntities a1, PedidoEntities a2)
            {
                Type t = typeof(PedidoEntities);
                PropertyInfo prop = t.GetProperty(sortExpression);
                object u1Value = prop.GetValue(a1, null);
                object u2Value = prop.GetValue(a2, null);
                return ((IComparable)u1Value).CompareTo(((IComparable)u2Value)) * sortDirection;
            });
        }

        protected void gvConsulta_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            pageNumber = e.NewPageIndex;
            PreencheGrid();
        }

        protected void gvConsulta_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            //switch (e.CommandName)
            //{
            //    case "Editar":
            //        this.ReadOnly = false;
            //        this.IdCidade = Convert.ToInt32(gvCidades.DataKeys[int.Parse(e.CommandArgument.ToString())]["IdCidade"].ToString());
            //        Server.Transfer("CidadeEdit.aspx", false);
            //        break;
            //    case "Visualizar":
            //        this.ReadOnly = true;
            //        this.IdCidade = Convert.ToInt32(gvCidades.DataKeys[int.Parse(e.CommandArgument.ToString())]["IdCidade"].ToString());
            //        Server.Transfer("CidadeEdit.aspx", false);
            //        break;
            //    default:
            //        break;
            //}
        }

        protected void gvConsulta_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //try
            //{
            //    if (e.Row.RowType == DataControlRowType.DataRow)
            //    {
            //        LinkButton lnkEditar = e.Row.FindControl("lnkEditar") as LinkButton;
            //        lnkEditar.CommandArgument = e.Row.RowIndex.ToString();
            //        ((ScriptManager)Master.FindControl("ScriptManager1")).RegisterPostBackControl(lnkEditar);

            //        LinkButton lnkVisualizar = e.Row.FindControl("lnkVisualizar") as LinkButton;
            //        lnkVisualizar.CommandArgument = e.Row.RowIndex.ToString();
            //        ((ScriptManager)Master.FindControl("ScriptManager1")).RegisterPostBackControl(lnkVisualizar);

            //ImageButton imgEditar = e.Row.FindControl("imgEditar") as ImageButton;
            //imgEditar.CommandArgument = e.Row.RowIndex.ToString();
            //((ScriptManager)Master.FindControl("ScriptManager1")).RegisterPostBackControl(imgEditar);

            //ImageButton imgVisualizar = e.Row.FindControl("imgVisualizar") as ImageButton;
            //imgVisualizar.CommandArgument = e.Row.RowIndex.ToString();
            //((ScriptManager)Master.FindControl("ScriptManager1")).RegisterPostBackControl(imgVisualizar);
            //    }
            //}
            //catch
            //{
            // Response.Redirect("~/sessaoExpirada.aspx", true);
            //}
        }

        protected void gvConsulta_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (sortExpression != e.SortExpression)
                sortDirection = 1; //ASC
            else
                sortDirection *= -1; //DESC

            sortExpression = e.SortExpression;
            PreencheGrid();
        }

        protected void btnAtualizarStatus_Click(object sender, EventArgs e)
        {
            try
            {
                PagSeguroFacade pagseguroFacade = new PagSeguroFacade(Server.MapPath("~/Configuration/PagSeguroConfig.xml"));

                DateTime dtIni = DateTime.Parse("01/" + txtDataIni.Text);
                DateTime dtFim = DateTime.Parse(DateTime.DaysInMonth(dtIni.Year, dtIni.Month) + "/" + txtDataIni.Text);

                TransactionSearchResult result = pagseguroFacade.ConsultaPorData(dtIni, dtFim, pageNumber);

                new PedidoFacade().AtualizaStatus(result);

                PreencheGrid();
            }
            catch (Exception ex)
            {
                gvConsulta.Visible = false;
                ((Label)Master.FindControl("lblMensagem")).Text = ex.Message;
                ((Label)Master.FindControl("lblMensagem")).CssClass = "failureNotification";
                ((Label)Master.FindControl("lblMensagem")).Visible = true;
            }
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                ExportarToExel("Consulta.xls");
            }
            catch (Exception ex)
            {
                gvConsulta.Visible = false;
                ((Label)Master.FindControl("lblMensagem")).Text = ex.Message;
                ((Label)Master.FindControl("lblMensagem")).CssClass = "failureNotification";
                ((Label)Master.FindControl("lblMensagem")).Visible = true;
            }
        }

        public void ExportarToExel(String fileName)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader(
                "content-disposition", string.Format("attachment; filename={0}", fileName));
            HttpContext.Current.Response.ContentType = "application/ms-excel";

            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    //  Create a form to contain the grid
                    Table table = new Table();

                    //  add the header row to the table
                    if (gvConsulta.HeaderRow != null)
                    {
                        PrepareControlForExport(gvConsulta.HeaderRow);
                        table.Rows.Add(gvConsulta.HeaderRow);
                    }

                    //  add each of the data rows to the table
                    foreach (GridViewRow row in gvConsulta.Rows)
                    {
                        PrepareControlForExport(row);
                        table.Rows.Add(row);
                    }

                    //  add the footer row to the table
                    if (gvConsulta.FooterRow != null)
                    {
                        PrepareControlForExport(gvConsulta.FooterRow);
                        table.Rows.Add(gvConsulta.FooterRow);
                    }

                    //  render the table into the htmlwriter
                    table.RenderControl(htw);

                    //  render the htmlwriter into the response
                    HttpContext.Current.Response.Write(sw.ToString());
                    HttpContext.Current.Response.End();
                }
            }

        }
        public override void VerifyRenderingInServerForm(Control control)
        {


        }

        private void PrepareControlForExport(Control control)
        {
            for (int i = 0; i < control.Controls.Count; i++)
            {
                Control current = control.Controls[i];
                if (current is LinkButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
                }
                else if (current is ImageButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
                }
                else if (current is HyperLink)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
                }
                else if (current is DropDownList)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
                }
                else if (current is CheckBox)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
                }

                if (current.HasControls())
                {
                    PrepareControlForExport(current);
                }
            }
        }

    }
}